#include "head.h"

void replace(int * buffer) {
	int count = rand()%N;
	int i;
	for (i = 0; i < count; i++) {
		buffer[rand()%N] = rand()%10;
	}
	printf("Nadpisano tablice, proces %d\n", getpid());
	for (i = 0; i < N; i++) {
		printf("%d ", buffer[i]);
	}
	printf("\n");
}

sem_t * semafor;        
int nr = 0;             // liczba procesów czytelników
int nw = 0;             // liczba procesów pisarzy
int write_request = 0; // liczba procesów chcących pisać

int main(int argc, char *argv[])
{
	int i, can_write;
	int * values;
	int val_fd;
	srand(time(NULL));
	if ((val_fd = shm_open(ARRAY, O_RDWR | O_CREAT, 0666)) == -1) {
		perror("shm_open");
		return -1;
	}
	if (ftruncate(val_fd, sizeof(int)*(N+1)) == -1) {
		perror("ftruncate");
		return -2;
	}
	if ((values = mmap(NULL, sizeof(int)*(N+1), PROT_READ | PROT_WRITE, MAP_SHARED, val_fd, 0)) == MAP_FAILED) {
		perror("mmap");
		return -3;
	}
	if ((semafor = sem_open(WRITER, O_RDWR | O_CREAT, 0666, 1)) == SEM_FAILED) {
		perror("sem_open");
	}

	for (i = 1; i < WRITER_COUNT; i++)
	{
		 pid_t pid = fork();
		 if (pid < 0) {
		 	perror("fork"); 
		 } else if (pid == 0) {
		 	 break;
		 }
		 sleep(1);
	}
	while(1) {
		can_write = 1;
		
		sem_wait (semafor);
		if(nr == 0 && nw == 0) {
			nw++;
		}
		else {
			can_write = 0;
		}
		sem_post(semafor);
		
		if(can_write) {
			replace(values);
			sleep(1);
			sem_wait(semafor);
			nw--;
			sem_post(semafor);
		}
		sleep(1);
	}
	sem_destroy(semafor);
	return 0;
}

